/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.manage.sell;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import shop.core.BaseController;
import shop.core.common.bean.JSONResult;
import shop.core.common.bean.ManageContainer;
import shop.core.common.dao.page.PagerModel;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.core.util.ExcelUtils;
import shop.services.manage.csrelation.CsrelationService;
import shop.services.manage.sell.SellService;
import shop.services.manage.sell.bean.Sell;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @类名称：SellAction
 * @创建人：Ltz
 * @创建时间：2017-08-29 下午22:07:31
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/manage/sell/")
public class SellAction extends BaseController<Sell> {
    private static final Logger logger = LoggerFactory.getLogger(SellAction.class);
    @Autowired
    private SellService sellService;
    @Autowired
    private CsrelationService csrelationService;
    @Autowired
    private UserService userService;
    private static final String page_toList = "/manage/sell/sellList";
    private static final String page_toEdit = "/manage/sell/sellEdit";

    public SellService getService() {
        return sellService;
    }

    private SellAction() {
        super.page_toList = page_toList;
        super.page_toAdd = null;
        super.page_toEdit = page_toEdit;
    }

    /**
     * 测试批量插入数据
     *
     * @return
     */
    @RequestMapping(value = "addTest", method = RequestMethod.GET)
    public JSONResult addTest() {
        JSONResult jsonResult = new JSONResult();
        List<Sell> insertList = new ArrayList<>();
        Sell sell = new Sell();
        for (int count = 0; count < 100000; count++) {
            sell.setCityID("" + count);
            insertList.add(sell);
        }
        getService().insert(insertList);
        jsonResult.setMessage("success");
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 跳转到编辑列表页面
     */
    @RequestMapping("toEditList")
    public String toEditList(HttpServletRequest request, ModelMap model, Sell sell) throws Exception {
        String time = request.getParameter("createTime");
        model.addAttribute("createTime", time.substring(0, 10));
        return page_toEdit;
    }

    /**
     * Excel文件上传方法
     */
    @RequestMapping(value = "excelUpload")
    public void upload(HttpServletRequest request, HttpServletResponse response, Sell sell) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //      获得文件：
        MultipartFile file = multipartRequest.getFile("file");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        //      获得输入流：
        InputStream in = file.getInputStream();
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        List<List<Object>> listob = ExcelUtils.getBankListByExcel(in, file.getOriginalFilename());
        List<Sell> sellList = new ArrayList<>();
        Sell creditInfoBean = null;
        for (int i = 0, length = listob.size(); i < length; i++) {
            List<Object> ob = listob.get(i);
            creditInfoBean = new Sell();
            creditInfoBean.setReportName(String.valueOf(ob.get(0)));
            creditInfoBean.setBrandID(String.valueOf(ob.get(1)));
            creditInfoBean.setKaID(String.valueOf(ob.get(2)));
            creditInfoBean.setCityID(String.valueOf(ob.get(3)));
            if (String.valueOf(ob.get(4)).contains(".")) {
                creditInfoBean.setStoreID(String.valueOf(ob.get(4)).substring(0, String.valueOf(ob.get(4)).lastIndexOf(".")));
            } else {
                creditInfoBean.setStoreID(String.valueOf(ob.get(4)));
            }
            creditInfoBean.setStoreName(String.valueOf(ob.get(5)));
            creditInfoBean.setProduct(String.valueOf(ob.get(6)));
            creditInfoBean.setBarCode(String.valueOf(ob.get(7)));
            String str = String.valueOf(ob.get(8));
            BigDecimal bd = new BigDecimal(str);
            creditInfoBean.setAmount(bd);
            creditInfoBean.setSales((int) Double.parseDouble(String.valueOf(ob.get(9))));
            creditInfoBean.setArea(String.valueOf(ob.get(10)));
            creditInfoBean.setCreateTime(sell.getCreateTime());
            creditInfoBean.setCreateUser(user.getNickname());
            creditInfoBean.setCityName(creditInfoBean.getCityID());
            sellList.add(creditInfoBean);
        }
        sellService.insert(sellList);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date2 = sdf.format(new Date());//日期格式化
        Sell rs = new Sell();
        rs.setCreateTime(date2);
        List<Sell> rsList = sellService.selectBrandList(rs);
        List<Sell> rsList2 = sellService.selectKaList(rs);
        List<Sell> rsList3 = sellService.selectCityList(rs);
        for (Sell sellInfo : rsList) {
            User user2 = new User();
            user2.setId(sellInfo.getBrandID());
            user2 = userService.selectOne(user2);
            //发送微信模版消息
            Map<String, String> msgParam = new HashMap<>();
            msgParam.put("first", "尊敬的" + user2.getNickname() + "，您的每日销售数据已更新，请及时查收！");
            msgParam.put("keyword1", sellInfo.getReportName());
            msgParam.put("keyword2", "已完成");
            msgParam.put("keyword3", rs.getCreateTime());
            msgParam.put("remark", "请登录平台查看数据信息！");
            WxMsgUtil.sendSellStatusMsg(msgParam, systemManager.getAccessToken(), user2.getOpenID());
        }
        for (Sell sellInfo : rsList2) {
            User user2 = new User();
            user2.setId(sellInfo.getKaID());
            user2 = userService.selectOne(user2);
            //发送微信模版消息
            Map<String, String> msgParam = new HashMap<>();
            msgParam.put("first", "尊敬的" + user2.getNickname() + "，您的每日销售数据已更新，请及时查收！");
            msgParam.put("keyword1", sellInfo.getReportName());
            msgParam.put("keyword2", "已完成");
            msgParam.put("keyword3", rs.getCreateTime());
            msgParam.put("remark", "请登录平台查看数据信息！");
            WxMsgUtil.sendSellStatusMsg(msgParam, systemManager.getAccessToken(), user2.getOpenID());
        }
        for (Sell sellInfo : rsList3) {
            User user2 = new User();
            user2.setId(sellInfo.getCityID());
            user2 = userService.selectOne(user2);
            //发送微信模版消息
            Map<String, String> msgParam = new HashMap<>();
            msgParam.put("first", "尊敬的" + user2.getNickname() + "，您的每日销售数据已更新，请及时查收！");
            msgParam.put("keyword1", sellInfo.getReportName());
            msgParam.put("keyword2", "已完成");
            msgParam.put("keyword3", rs.getCreateTime());
            msgParam.put("remark", "请登录平台查看数据信息！");
            WxMsgUtil.sendCitySellStatusMsg(msgParam, systemManager.getAccessToken(), user2.getOpenID());
        }
        in.close();
        PrintWriter out = null;
        response.setCharacterEncoding("utf-8");  //防止ajax接受到的中文信息乱码
        out = response.getWriter();
        out.print("文件导入成功！");
        out.flush();
        out.close();
    }

    /**
     * 根据日期下载某天上传的Excel文件
     */
    @RequestMapping(value = "/excelDownload", method = RequestMethod.GET)
    public void outExcel(HttpServletRequest request, HttpServletResponse response, Sell sell) throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException {
        response.reset();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
        String dateStr = sdf.format(new Date());
        // 指定下载的文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + dateStr + ".xlsx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        logger.debug("查询数据库开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<Sell> creditInfoList = sellService.selectListByDate(sell);
        logger.debug("查询数据库结束时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<Sell> ems = new ArrayList<>();
        Map<Integer, List<Sell>> maps = new LinkedHashMap<>();
        SXSSFWorkbook book = null;
        ems.add(new Sell("报表名称", "reportName", 0));
        ems.add(new Sell("品牌商", "brandName", 0));
        ems.add(new Sell("KA经理", "kaName", 0));
        ems.add(new Sell("城市合伙人", "cityName", 0));
        ems.add(new Sell("店号", "storeID", 0));
        ems.add(new Sell("店铺名称", "storeName", 0));
        ems.add(new Sell("商品名称", "product", 0));
        ems.add(new Sell("条形码", "barCode", 0));
        ems.add(new Sell("销售金额", "amount", 0));
        ems.add(new Sell("销售数量", "sales", 0));
        ems.add(new Sell("城市", "area", 0));
        maps.put(0, ems);
        try {
            logger.debug("创建文件开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            book = ExcelUtils.createExcelFile(Sell.class, creditInfoList, maps, "销售表");
            logger.debug("创建文件结束时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (IllegalArgumentException | IllegalAccessException
                | InvocationTargetException | ClassNotFoundException
                | IntrospectionException | ParseException e1) {
            e1.printStackTrace();
        }
        OutputStream output;
        try {
            output = response.getOutputStream();

            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            //刷新此缓冲的输出流，保证数据全部都能写出
            bufferedOutPut.flush();
            book.write(bufferedOutPut);
            bufferedOutPut.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据日期批量删除每天上传的Excel文件
     */
    @RequestMapping(value = "deletesByTimes", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deletesByTimes(@RequestParam(value = "times[]") String[] times) {
        JSONResult jsonResult = new JSONResult();
        if (times == null || times.length == 0) {
            throw new NullPointerException("选择时间不能全为空！");
        } else {
            for (int i = 0; i < times.length; i++) {
                sellService.deletesByTimes(times[i].substring(0, 10));
            }
            jsonResult.setSuccess(true);
        }
        return jsonResult;
    }

    /**
     * 根据id删除某条记录
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult delete(HttpServletRequest request, @ModelAttribute("e") Sell e) throws Exception {
        JSONResult jsonResult = new JSONResult();
        getService().delete(e);
        jsonResult.setMessage("success");
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 新增批量查询方法
     * 根据日期批量查询某天上传的Excel所有数据
     */
    @RequestMapping("loadDataDetail")
    @ResponseBody
    public PagerModel loadDataDetail(HttpServletRequest request, Sell e) {
        int offset = 0;                     //每一页开始的偏移量
        int pageSize = 10;                  //每一页的个数
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = getService().selectPageListDetail(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 验证当前选择的日期报表时间是否已经存在
     *
     * @param sell
     * @return
     */
    @RequestMapping(value = "toValid", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult toValid(Sell sell) {
        List<Sell> rsList = sellService.selectListByDate(sell);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }


    /**
     * 新增批量查询方法
     * 根据日期批量查询某天上传的Excel所有数据
     */
    @Override
    @RequestMapping("loadData")
    @ResponseBody
    public PagerModel loadData(HttpServletRequest request, Sell e) {
        int offset = 0;                     //每一页开始的偏移量
        int pageSize = 10;                  //每一页的个数
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = getService().selectPageList(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }
}
